<template>
	<div class="boxStyle">
		<el-row type="flex" class="row-bg" justify="start" style="margin-bottom: 10px;">
			<el-col :span="1" v-if="addShow!==-1">
				<el-button type="warning" size="small" @click="add" icon="el-icon-plus">新增</el-button>
			</el-col>
		</el-row>
		<el-table ref="multipleTable" border stripe :data="tableLists" tooltip-effect="dark" style="margin-bottom: 10px;width: 100%">
			<el-table-column type="selection" width="55"></el-table-column>
			<el-table-column prop="role" label="角色名称" width="120"></el-table-column>
			<el-table-column prop="description" label="角色描述" width="120"></el-table-column>
			<el-table-column prop="resourceNames" label="拥有资源" width="1000"></el-table-column>
			<el-table-column label="操作" min-width="120">
				<template slot-scope="scope">
					<el-button size="mini" type="primary" @click="update(scope.$index,scope.row.id)" v-if="updateShow!==-1">更新信息</el-button>
					<el-button size="mini" type="danger" style="margin-top: 5px;margin-left: 0px;" @click="del(scope.row.id)" v-if="scope.row.id!==1&&deleShow!==-1">删除信息</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination background @current-change="handleCurrentChange" :current-page="currentPage" :page-size="size" layout="prev, pager, next,total, slot" :total="totals">
			<span style="margin-top: -2px;color: #606266;font-weight: 100;">第<el-input type="text" v-model="inputPage" style="width: 60px;margin: 0 5px;"/>页<el-button size="mini" style="background: #409EFF; color: #fff;margin:0 5px;" @click="handleCurrentChange(inputPage)">跳转</el-button><span>总计{{totalPage}}页</span></span>
		</el-pagination>
		<div class="modal fade" id="role" tabindex="-1" role="dialog" data-keyboard="false">
			<div class="modal-dialog" role="document">
				<div class="modal-content" style="width:800px;height: 300px;">
					<div class="modal-header" style="border-radius: 4px;">
						<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
						<ul class="nav nav-tabs role" role="tablist">
							<li role="presentation" class="active">
								<a href="#qusInfo" aria-controls="qusInfo" role="tab" data-toggle="tab">新增/编辑</a>
							</li>
						</ul>
					</div>
					<div class="modal-body" style="padding-right: 60px;height:170px;">
						<div class="tab-content">
							<div role="tabpanel" class="tab-pane active" id="qusInfo">
								<el-form :model="ruleRole" :rules="rules" ref="ruleRole" label-width="100px" class="demo-ruleForm" @submit.native.prevent>
									<input type="hidden" name="id" v-model="id">
									<input type="hidden" name="resourceIds" id="resourceIds" v-model="resourceIds" />
									<el-col :span="12">
										<el-form-item label="角色名:" prop="roleName">
											<el-input v-model="ruleRole.roleName" size="small"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="角色描述:" prop="description">
											<el-input v-model="ruleRole.description" size="small"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="拥有资源:" prop="resourceName">
											<input type="text" class="form-control form-filter input-sm" id="resourceName" name="resourceName" v-model="ruleRole.resourceName" style="width: 266px; height: 30px;" />
											<a style="color: red" id="menuBtn" href="javascript:void(0);" @click="showMenu($event);">选择</a>
											<div class="ztreeBox" id="ztreeBox">
												<ul id="roleZtree" class="ztree"></ul>
											</div>
										</el-form-item>
									</el-col>
								</el-form>
							</div>
						</div>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-success" id="save" @click="save('ruleRole')">保存</button>
						<button type="button" class="btn btn-success" id="usave" @click="uSave('ruleRole')">保存</button>
						<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					</div>
				</div>
			</div>
			<div></div>
		</div>
	</div>
</template>

<script>
	import axios from "axios"
	import qs from "qs"
	import "static/global/plugins/ztree/zTreeStyle/zTreeStyle.css"
	import "static/global/plugins/ztree/jquery.ztree.core.min.js"
	import "static/global/plugins/ztree/jquery.ztree.excheck.min.js"
	export default {
		data() {
			return {
				tableLists: [],
				purl: this.$store.state.purl,
				currentPage: 1,
				totals: 0, //分页总条数
				size: 0, //每页条数
				updateShow: 0, //是否显示更新信息
				addShow: 0, //是否显示新增
				deleShow:0,
				id: "",
				ruleRole: {
					roleName: "",
					description: "",
					resourceName: ""
				},
				rules: {
					roleName: [{
						required: true,
						message: "请输入角色名",
						trigger: 'change'
					}],
					description: [{
						required: true,
						message: "请输入角色描述",
						trigger: 'change'
					}],
					resourceName: [{
						required: true,
						message: "请选择权限",
						trigger: 'change'
					}]
				},
				inputPage: 1,
				totalPage: 0, //总页数
				resourceIds: "",
				setting: {
					check: {
						enable: true,
						chkboxType: {
							"Y": "",
							"N": ""
						}
					},
					view: {
						dblClickExpand: false
					},
					data: {
						simpleData: {
							enable: true
						}
					},
					callback: {
						onCheck: this.onCheck
					}
				}
			}
		},
		activated() {
			this.load(1);
			this.inputPage = this.currentPage;
			this.addShow = this.purl[0].findIndex((val) => val === "/interface/role/showCreateForm") //判断是否拥有增加权限
			this.updateShow = this.purl[0].findIndex((val) => val === "/interface/role/showUpdateForm") //判断是否拥有更新权限
			this.deleShow = this.purl[0].findIndex((val) => val === "/interface/role/delete")
		},
		methods: {
			load(num) {
				axios.get("interface/role?pageNo=" + num + "").then((res) => {
					this.tableLists = res.data.data.sysRoles; //list数据
					this.totals = res.data.data.pageBean.totalRow; //总条数
					this.size = res.data.data.pageBean.pageSize; //每页条数
					this.totalPage = res.data.data.pageBean.totalPage; //总页数
				})
			},
			handleCurrentChange(val) {
				this.currentPage = val - 0;
				this.inputPage = val;
				axios.get("interface/organization?pageNo=" + val).then((res) => {
					this.tableLists = res.data.data.sysOrganizations;
					this.totals = res.data.data.pageBean.totalRow; //总条数
					this.size = res.data.data.pageBean.pageSize; //每页条数
					this.totalPage = res.data.data.pageBean.totalPage; //总页数
				})
			},
			add() {
				$("#role").modal("show")
//				$(".role li a").text("新增角色信息")
				$("#save").show();
				$("#usave").hide();
				//树
				axios.get("interface/role/showCreateForm").then((res) => {
					var ztreeData = [];
					res.data.data.forEach((ele, idx) => {
						if(ele.rootNode) {
							return;
						} else {
							ztreeData.push({
								id: ele.id,
								pId: ele.parentId,
								name: ele.name,
								checked: ele.checked
							})
						}
					})
					$.fn.zTree.init($("#roleZtree"), this.setting, ztreeData)
				});
			},
			save(formname) {
				this.$refs[formname].validate((valid) => {
					if(valid) {
						var params = {
							role: this.ruleRole.roleName,
							description: this.ruleRole.description,
							resourceIds: this.resourceIds,
							resourceNames: this.ruleRole.resourceName
						}
						axios({
							method: 'post',
							url: 'interface/role/save',
							data: params,
							headers: {
								'Content-Type': 'application/json'
							}
						}).then((res) => {
							if(res.data.code == 1) {
								this.load(this.currentPage);
								$("#role").modal("hide");
								this.$message.success("新增成功");
							} else {
								$("#role").modal("hide");
								this.$alert(res.data.msg, '提示', {
									confirmButtonText: '确定',
									type: 'warning',
									callback: action => {
										$("#role").modal("show");
									}
								})
							}
						});
					} else {
						return false;
					}
				})
			},
			update(index, id) {
				$("#role").modal("show")
//				$(".role li a").text("更新角色信息")
				$("#save").hide();
				$("#usave").show();
				this.id = id;
				this.ruleRole.roleName=this.tableLists[index].role;
				this.ruleRole.description=this.tableLists[index].description;
				this.resourceIds=this.tableLists[index].resourceIds;
				this.ruleRole.resourceName=this.tableLists[index].resourceNames;
				axios.get("interface/role/showUpdateForm?id="+id).then((res) => {
					var ztreeData = [];
					res.data.data.sysResources.forEach((ele, idx) => {
						if(ele.rootNode) {
							return;
						} else {
							ztreeData.push({
								id: ele.id,
								pId: ele.parentId,
								name: ele.name,
								checked: ele.checked
							})
						}
					})
					$.fn.zTree.init($("#roleZtree"), this.setting, ztreeData)
				});
			},
			uSave(formname) {
				this.$refs[formname].validate((valid) => {
					if(valid) {
						var params = {
							id:this.id,
							role: this.ruleRole.roleName,
							description: this.ruleRole.description,
							resourceIds: this.resourceIds,
							resourceNames: this.ruleRole.resourceName
						}
						axios({
							method: 'post',
							url: 'interface/role/save',
							data: params,
							headers: {
								'Content-Type': 'application/json'
							}
						}).then((res) => {
							this.load(this.currentPage);
							$("#role").modal("hide");
							this.$message.success("更新成功");
						});
					} else {
						return false;
					}
				})
			},
			del(id) {
				this.$confirm('确认要删除此条数据吗?', '删除警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					axios.post("interface/role/delete?roleId=" + id).then((res) => {
						this.load(1)
					})
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
				});
			},
			showMenu(e) {
				$("body").bind("mousedown", this.onBodyDown);
				$(".ztreeBox").slideDown("fast")
			},
			onCheck(e, treeId, treeNode) {
				var zTree = $.fn.zTree.getZTreeObj("roleZtree"),
					nodes = zTree.getCheckedNodes(true),
					id = "",
					name = "";
				nodes.sort(function compare(a, b) {
					return a.id - b.id;
				});
				for(var i = 0, l = nodes.length; i < l; i++) {
					id += nodes[i].id + ",";
					name += nodes[i].name + ",";
				}
				if(id.length > 0) id = id.substring(0, id.length - 1);
				if(name.length > 0) name = name.substring(0, name.length - 1);
				this.resourceIds = id;
				this.ruleRole.resourceName = name;
			},
			hideMenu() {
				$(".ztreeBox").fadeOut("fast");
				$("body").unbind("mousedown", this.onBodyDown);
			},
			onBodyDown(event) {
				if(!((event.target.id == "menuBtn" || event.target.id == "ztreeBox" || $(event.target).parents("#ztreeBox").length > 0))) {
					this.hideMenu();
				}
			}
		}
	}
</script>

<style>
	.ztreeBox {
		position: absolute;
		background: white;
		display: none;
		z-index: 10052;
		width: 200px;
		height: 200px;
		overflow: auto;
	}
</style>